/**
 * 防抖节流
 * @param {*} action 回调
 * @param {*} delay 等待的时间
 * @param {*} context this指针
 * @param {Boolean} isThrottle 是否等待上一次, 默认为false就是debounce效果，设置为true就是throttle效果
 * @returns {Function}
 */
function debounce(action, delay, immediate, isThrottle) {
  let timeout
  let lastTamp
  let context
  let args
  return function() {
    context = this
    args = arguments

    if (timeout) {
      if (isThrottle) {
        return
      } else {
        clearTimeout(timeout)
      }
    }

    let elapsed = Date.now() - lastTamp

    if (isThrottle && elapsed >= delay) {
      runCallback()
    } else {
      if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(function() {
          timeout = null
        }, delay)
        if (callNow) action.apply(context, args)
      } else {
        timeout = setTimeout(runCallback, delay)
      }
    }
    /**
     * 执行回调
     */
    function runCallback() {
      lastTamp = Date.now()
      timeout = null
      action.apply(context, args)
    }
  }
}

// function debounce(action, delay, immediate) {
//   let timeout
//   return function() {
//     let args = arguments
//     let context = this
//     clearTimeout(timeout)
//     timeout = setTimeout(function(){
//       action.apply(context, args)
//     }, delay)
//   }
// }

// function trottle(action, delay) {
//   let previous = 0
//   return function() {
//     var context = this
//     var args = arguments
//     var now = +new Date()

//     if(now - previous > delay) {
//       action.apply(context, args)
//       previous = now
//     }
//   }
// }

// function trottle(action, delay) {
//   var timeout
//   return function() {
//     var args = arguments
//     var context = this
//     if (!timeout) {
//       timeout = setTimeout(function(){
//         timeout = null
//         actions.apply(context, args)
//       }, delay)
//     }
//   }
// }
